// todo:  CacheInterceptor，用于在通过 Dio 发起网络请求时，对响应数据进行缓存，减少对服务器的重复请求。
// todo: 实现缓存数据，缓存检查
import 'dart:io';

import 'package:dio/dio.dart';
import '../config/api_constants.dart';
import '../models/api_response.dart';

class CacheInterceptor extends InterceptorsWrapper {
  CacheInterceptor()
      : super(
          // * (response) 将响应数据缓存起
          onResponse: (
            Response<dynamic> response,
            ResponseInterceptorHandler handler,
          ) async {
            final String key = response.requestOptions.uri.toString();

            // 1.只有当服务器返回 200 状态码时，数据才会被缓存
            if (response.statusCode == HttpStatus.ok) {
              // 2.将响应数据封装为 CachedResponse 对象
              final CachedResponse<dynamic> cachedResponse =
                  CachedResponse<dynamic>.fromResponse(response);
              // 3.以请求的 URI path 作为键，将数据存入 _cache，实现缓存存储
              _cache[key] = cachedResponse;
            }

            return handler.next(response);
          },
          // * (request)每次请求都会先检查缓存中是否存在有效数据，若存在则直接返回缓存数据，避免重复请求
          onRequest: (
            RequestOptions options,
            RequestInterceptorHandler handler,
          ) async {
            final String key = options.uri.toString();
            final CachedResponse<dynamic>? cachedResponse = _cache[key];

            if (cachedResponse != null &&
                DateTime.now()
                        .difference(cachedResponse.setDateTime)
                        .inSeconds <
                    _delay.inSeconds) {
              return handler.resolve(cachedResponse);
            }

            return handler.next(options);
          },
        );

  static const Duration _delay =
      AppDurations.oneMinute; // _delay 是缓存数据的有效时间，这里设置为 1 分钟
  static final Map<String, CachedResponse<dynamic>> _cache =
      <String, CachedResponse<dynamic>>{};

  // 打印缓存中的所有数据
  void printCache() {
    _cache.forEach((key, value) {
      print('Cache Key: $key');
      print('Cached Data: ${value.data}');
      print('Cache Set Time: ${value.setDateTime}');
    });
  }

  // 根据 URI 获取缓存数据
  CachedResponse<dynamic>? getCacheData(String uri) {
    return _cache[uri];
  }
}
